package com.rkc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rkc.config.RabbitMQConfiguration;
import com.rkc.enums.BizCodeEnum;
import com.rkc.enums.CouponStateEnum;
import com.rkc.enums.ProductOrderStateEnum;
import com.rkc.enums.StockTaskStateEnum;
import com.rkc.exception.BizException;
import com.rkc.feign.ProductOrderFeignService;
import com.rkc.interceptor.LoginInterceptor;
import com.rkc.mapper.CouponRecordMapper;
import com.rkc.mapper.CouponTaskMapper;
import com.rkc.model.CouponRecordDO;
import com.rkc.model.CouponRecordMessage;
import com.rkc.model.CouponTaskDO;
import com.rkc.model.LoginUser;
import com.rkc.request.LockCouponRecordRequest;
import com.rkc.service.CouponRecordService;
import com.rkc.utils.JsonData;
import com.rkc.vo.CouponRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 冉堃赤
 * @since 2021-10-22
 */
@Slf4j
@Service
public class CouponRecordServiceImpl implements CouponRecordService {

    @Resource
    private CouponRecordMapper couponRecordMapper;

    @Resource
    private CouponTaskMapper couponTaskMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitMQConfiguration rabbitMQConfiguration;

    @Autowired
    private ProductOrderFeignService productOrderFeignService;

    @Override
    public Map<String, Object> page(int page, int size) {
        LoginUser loginUser = LoginInterceptor.THREAD_LOCAL.get();
        Page<CouponRecordDO> pageInfo = new Page<>();
        Page<CouponRecordDO> couponRecordDOPage = couponRecordMapper.selectPage(pageInfo, new QueryWrapper<CouponRecordDO>().eq("user_id", loginUser.getId())
                .orderByDesc("create_time"));
        Map<String, Object> pageMap = new HashMap<>(3);
        pageMap.put("total_record", couponRecordDOPage.getTotal());
        pageMap.put("total_page", couponRecordDOPage.getPages());
        pageMap.put("current_data", couponRecordDOPage.getRecords().stream().map(this::beanProcess).collect(Collectors.toList()));
        return pageMap;
    }

    @Override
    public CouponRecordVO findById(long id) {
        LoginUser loginUser = LoginInterceptor.THREAD_LOCAL.get();
        CouponRecordDO couponRecordDO = couponRecordMapper.selectOne(new QueryWrapper<CouponRecordDO>().eq("id", id).eq("user_id", loginUser.getId()));
        return couponRecordDO == null ? null : beanProcess(couponRecordDO);
    }

    /**
     * 锁定优惠券
     * 1）锁定优惠券记录
     * 2）task表插入记录
     * 3）发送延时消息
     * @param recordRequest
     * @return
     */
    @Override
    public JsonData lockCouponRecords(LockCouponRecordRequest recordRequest) {
        String orderOutTradeNo = recordRequest.getOrderOutTradeNo();
        List<Long> lockCouponRecordIds = recordRequest.getLockCouponRecordIds();
        LoginUser loginUser = LoginInterceptor.THREAD_LOCAL.get();
        int updateRows = couponRecordMapper.lockUseStateBatch(loginUser.getId(), CouponStateEnum.USED.name(), lockCouponRecordIds);
        //根据使用的优惠券生成CouponTaskDO
        List<CouponTaskDO> couponTaskDOList = lockCouponRecordIds.stream().map(obj -> {
            CouponTaskDO couponTaskDO = new CouponTaskDO();
            couponTaskDO.setCreateTime(new Date());
            couponTaskDO.setOutTradeNo(orderOutTradeNo);
            couponTaskDO.setCouponRecordId(obj);
            couponTaskDO.setLockState(StockTaskStateEnum.LOCK.name());
            return couponTaskDO;
        }).collect(Collectors.toList());
        int insertRows = couponTaskMapper.insertBatch(couponTaskDOList);
        log.info("优惠券记录锁定updateRows={}", updateRows);
        log.info("新增优惠券记录task insertRows={}", insertRows);
        if (lockCouponRecordIds.size() == insertRows && insertRows == updateRows) {
            //发送延时消息
            for (CouponTaskDO couponTaskDO : couponTaskDOList) {
                CouponRecordMessage couponRecordMessage = new CouponRecordMessage();
                couponRecordMessage.setOutTradeNo(couponTaskDO.getOutTradeNo());
                couponRecordMessage.setTaskId(couponTaskDO.getId());
                rabbitTemplate.convertAndSend(rabbitMQConfiguration.getEventExchange(), rabbitMQConfiguration.getCouponReleaseDelayRoutingKey(),
                        couponRecordMessage);
                log.info("优惠券锁定延时消息发送成功：{}", couponRecordMessage);
            }
            return JsonData.buildSuccess();
        }
        throw new BizException(BizCodeEnum.COUPON_RECORD_LOCK_FAIL);
    }

    /**
     * 解锁优惠券记录
     * 1）查询task工作单是否存在
     * 2）查询订单状态
     * @param couponRecordMessage
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean releaseCouponRecord(CouponRecordMessage couponRecordMessage) {
        //查询工作单
        CouponTaskDO couponTaskDO = couponTaskMapper.selectOne(new QueryWrapper<CouponTaskDO>().eq("id", couponRecordMessage.getTaskId()));
        if (couponTaskDO == null) {
            log.warn("工作单不存在，消息：{}", couponRecordMessage);
            return true;
        }
        //只对lock状态下的进行解锁
        if (couponTaskDO.getLockState().equalsIgnoreCase(StockTaskStateEnum.LOCK.name())) {
            JsonData jsonData = productOrderFeignService.queryProductOrderState(couponRecordMessage.getOutTradeNo());
            if (jsonData.getCode() == 0) {
                //正常响应，判断订单状态
                String state = jsonData.getData().toString();
                if (ProductOrderStateEnum.NEW.name().equalsIgnoreCase(state)) {
                    //状态还是NEW，返回消息队列，重新处理，正常情况是不会走到这的
                    log.warn("订单状态是NEW，返回消息队列，重新投递：{}", couponRecordMessage);
                    return false;
                }
                if (ProductOrderStateEnum.PAY.name().equalsIgnoreCase(state)) {
                    //已经支付的订单，修改task状态为FINISH
                    couponTaskDO.setLockState(StockTaskStateEnum.FINISH.name());
                    couponTaskMapper.updateById(couponTaskDO);
                    log.info("订单已经支付，修改库存锁定工作单为FINISH状态：{}", couponRecordMessage);
                    return true;
                }
            }
            //订单不存在
            log.warn("订单被取消或删除，确认消息，修改task状态为CANCEL，恢复优惠券使用状态为NEW，message：{}", couponRecordMessage);
            //将锁状态改为取消
            couponTaskDO.setLockState(StockTaskStateEnum.CANCEL.name());
            couponTaskMapper.updateById(couponTaskDO);
            //恢复优惠券USED状态为NEW状态
            couponRecordMapper.updateUsedState(couponTaskDO.getCouponRecordId(), CouponStateEnum.NEW.name());
            return true;
        }
        log.warn("工作单状态不是lock，state={}，消息体={}", couponTaskDO.getLockState(), couponRecordMessage);
        couponTaskDO.setLockState(StockTaskStateEnum.CANCEL.name());
        couponTaskMapper.updateById(couponTaskDO);
        couponRecordMapper.updateState(couponTaskDO.getCouponRecordId(), CouponStateEnum.NEW.name());
        return true;
    }

    private CouponRecordVO beanProcess(CouponRecordDO obj) {
        CouponRecordVO couponRecordVO = new CouponRecordVO();
        BeanUtils.copyProperties(obj, couponRecordVO);
        return couponRecordVO;
    }
}
